package com.five.community.service.impl;

import com.five.community.bean.Role;
import com.five.community.mapper.PermissionMapper;
import com.five.community.mapper.RoleMapper;
import com.five.community.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Map<String, Object>> selectRoleAndPermissions() throws Exception {

        List<Map<String, Object>> rolePermissions =
                new ArrayList<>();

        // ① 角色表：查询所有的角色
        List<Role> roles = roleMapper.selectAll();

        for (Role role : roles) {

            Map<String, Object> rolePermission = new HashMap<>();
            rolePermission.put("rid", role.getId());
            rolePermission.put("rname", role.getName());

            // ② 角色权限表： 通过角色的id，查询对于的所有的权限id
            List<Long> rolePermissionIds = roleMapper.selectPIdsByRId(role.getId());
            List<String> permissonNames = new ArrayList<>();
            for (Long rolePermissionId : rolePermissionIds) {
                // ③ 权限表： 通过权限的id，查询权限名称
                String permissionName = permissionMapper.selectNameById(rolePermissionId);
                permissonNames.add(permissionName);
            }
            rolePermission.put("permissonNames", permissonNames);

            rolePermissions.add(rolePermission);
        }

        // ④ 数组组装List<Map<String, Object>>

        return rolePermissions;
    }

    @Transactional
    @Override
    public void insertRole(String rname, long[] pids) throws Exception {

        // ① 角色：插入数据
        Role role = new Role();
        role.setName(rname);
        roleMapper.insert(role);

        int x = 1/0;

        // ② 往中间表：插入数据
        for (long pid : pids) {
            roleMapper.insertPermission(role.getId(), pid);
        }

    }

    @Override
    public List<Role> selectAll() throws Exception {

        return roleMapper.selectAll();
    }

    @Override
    public Role selectById(int id) throws Exception {
        return roleMapper.selectById(id);
    }
}